﻿// 首页加载完后，取消加载中状态
$(window).load(function () {
    $("#loading").fadeOut();
    $("#MyUserNameIndex").iMenubutton({
        iconCls: 'fa fa-user',
        hasDownArrow: false,
        text: $.dm.getUserInfo().userName
    });

    // 加载语言 根据样式进行变动
    var lang = $.dm.getLangName();
    if (!lang || lang == 'zh-CN') {
        // $("#YdmCoreIndexNavRight").css("width", "450px");
    }

    // 添加拖动tab的事件
    $("#index_tabs").tabs({
        onAdd: function () {
            $("#index_tabs").tabs("enableDnd");
        },
        onBeforeDrag: function (title, index) {
        }
    });
    $("#index_tabs").tabs("enableDnd");

    // 绑定返回按钮的tooltip
    $('#btnGotoPreTab').tooltip({
        position: 'bottom',
        content: ' ctrl+q 查询菜单<br/> ctrl+alt+q 返回上一页签 <br/> ctrl+alt+w 关闭当前页签 <br/> 页签可拖动排序',
    });
});
var isFullScreen = false;

var App = function () {
    var setFullScreen = function () {
        var docEle = document.documentElement;
        if (docEle.requestFullscreen) {
            //W3C
            docEle.requestFullscreen();
        } else if (docEle.mozRequestFullScreen) {
            //FireFox
            docEle.mozRequestFullScreen();
        } else if (docEle.webkitRequestFullScreen) {
            //Chrome等
            docEle.webkitRequestFullScreen();
        } else if (docEle.msRequestFullscreen) {
            //IE11
            docEle.msRequestFullscreen();
        } else {
            $.iMessager.alert('温馨提示', '该浏览器不支持全屏', 'messager-warning');
        }
    };

    //退出全屏 判断浏览器种类
    var exitFullScreen = function () {
        // 判断各种浏览器，找到正确的方法
        var exitMethod = document.exitFullscreen || //W3C
            document.mozCancelFullScreen ||    //Chrome等
            document.webkitExitFullscreen || //FireFox
            document.msExitFullscreen; //IE11
        if (exitMethod) {
            exitMethod.call(document);
        }
        else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    };

    return {
        init: function () {

        },
        handleFullScreen: function () {
            if (isFullScreen) {
                exitFullScreen();
                isFullScreen = false;
            } else {
                setFullScreen();
                isFullScreen = true;
            }
        }
    };
};

$(function () {
    $("#MyCollapseMenu").on("click", function () {
        var panel = $('#index_layout').iLayout('panel', 'west');
        var westCollapsed = panel.panel('options').collapsed;
        if (westCollapsed === true) {
            // 展开
            showWest();
        } else {
            // 折叠
            hideWest();
        }
    });

    // 首页tabs选项卡
    var index_tabs = $('#index_tabs').iTabs({
        fit: true,
        tools: [{
            iconCls: 'fa fa-bullhorn',
            id: 'btnGotoPreTab',
            handler: function () {
                chgPreIndexTab();
            }
        }, {
            iconCls: 'fa fa-home',
            handler: function () {
                $('#index_tabs').iTabs('select', 0);
            }
        }, {
            iconCls: 'fa fa-refresh',
            handler: function () {
                var refresh_tab = $('#index_tabs').iTabs('getSelected');
                var refresh_iframe = refresh_tab.find('iframe')[0];
                refresh_iframe.contentWindow.location.href = refresh_iframe.src;
                //$('#index_tabs').trigger(TOPJUI.eventType.initUI.base);

                //var index = $('#index_tabs').iTabs('getTabIndex', $('#index_tabs').iTabs('getSelected'));
                //console.log(index);
                //$('#index_tabs').iTabs('getTab', index).iPanel('refresh');
            }
        }, {
            iconCls: 'fa fa-close',
            handler: function () {
                var index = $('#index_tabs').iTabs('getTabIndex', $('#index_tabs').iTabs('getSelected'));
                var tab = $('#index_tabs').iTabs('getTab', index);
                if (tab.iPanel('options').closable) {
                    $('#index_tabs').iTabs('close', index);
                }
            }
        }, {
            iconCls: 'fa fa-expand',
            handler: function () {
                $("#north").slideToggle("100", function () {
                    $("#west").resize();
                });
            }
        },
        {
            iconCls: 'fa fa-arrows-alt',
            handler: function () {
                App().handleFullScreen();
            }
        }],
        //监听右键事件，创建右键菜单
        onContextMenu: function (e, title, index) {
            e.preventDefault();
            if (index >= 0) {
                $('#mm').iMenu('show', {
                    left: e.pageX,
                    top: e.pageY
                }).data("tabTitle", title);
            }
        }
    });

    //tab右键菜单
    $("#mm").iMenu({
        onClick: function (item) {
            tabMenuOprate(this, item.name);
        }
    });

    // 初始化accordion
    $("#RightAccordion").iAccordion({
        fit: false,
        border: false,
        multiple: false
    });

    // 绑定横向导航菜单点击事件
    //$(".systemName").on("click", function (e) {
    //    //generateMenu(e.currentTarget.dataset.menuid, e.target.textContent); //IE9及以下不兼容data-menuid属性
    //    //generateMenu(e.target.getAttribute('data-menuid'), e.target.textContent);
    //    generateMenu($(this).attr("id"), $(this).attr("title"));
    //    $(".systemName").removeClass("selected");
    //    $(this).addClass("selected");
    //});

    // 导航栏
    hideNavBtn();
    $(window).resize(function () {
        setTimeout(function () {
            hideNavBtn();
        }, 400)
    });
    $(".nav-right-btn").on('click', function () {
        navsScrollTo("next");
    });
    $(".nav-left-btn").on('click', function () {
        navsScrollTo("previous");
    });
    $(".nav-group").on("click", 'li', function (e) {
        //添加选择样式
        //$(".nav-group .selected").removeClass("selected");
        //$(this).addClass("selected");
        navsScrollTo("first", this);
        // 刷新左侧导航菜单
        var id = $(this).attr('id');
        var title = $(this).attr('title');
        if (id && title) {
            generateMenu(id, title);
        }
    });
    var changing = false; //是否正在滚动中
    function navsScrollTo(step, target) {
        if (changing) {
            return
        } else {
            changing = !changing;
            setTimeout(function () {
                changing = !changing;
            }, 400);
        }

        var contentWidth, itemWidth, areaWidth, currentLeft, times, $navContentBox;
        $navContentBox = $(".nav-group"); // 拿到导航项的盒子
        //1.得到滚动内容的总长度 contentWidth；
        contentWidth = parseInt($navContentBox.width());

        //2.得到滚动元素的宽度 itemWidth；
        // itemWidth = 102;
        itemWidth = $(".nav-center ul li").width() + 2;

        //3.得到当前currentLeft值
        currentLeft = parseInt($navContentBox.position().left);

        //4.得到滚动区域的总长度 areaWidth;
        areaWidth = parseInt($navContentBox.parent().width());

        //5.按钮是否生效  并左右滚动
        if (step == 'next') { // 滚动到下一页
            if (areaWidth + Math.abs(currentLeft) < contentWidth) { // 不需要向右移动
                // 5.1 移动多少个
                times = Math.floor(areaWidth / itemWidth);
                $navContentBox.css('left', currentLeft - itemWidth * times)
            }
        } else if (step == 'previous') {
            // 滚动到上一页
            if (currentLeft != 0) {
                if (Math.abs(currentLeft) <= areaWidth) {
                    $navContentBox.css('left', 0)
                } else {
                    times = Math.floor(areaWidth / itemWidth);
                    $navContentBox.css('left', -(Math.abs(currentLeft) - itemWidth * times))
                }
            }
        } else if (step == 'first') {//将点击的元素滚动到第一个
            liLeft = $(target).position().left;
            //获取点击项距离浏览器右侧的距离
            var liRight = $(".nav-bar").width() - $(target).offset().left - itemWidth - $('.nav-right').width();
            if (liRight < itemWidth && areaWidth + Math.abs(currentLeft) < contentWidth) {
                $navContentBox.css('left', -liLeft)
            }
        }
    }
    function hideNavBtn() {
        var contentWidth, areaWidth;
        var $navContentBox = $(".nav-group");
        //1.得到滚动内容的总长度 contentWidth；
        contentWidth = parseInt($navContentBox.width());

        //2.得到滚动区域的总长度 areaWidth;
        areaWidth = parseInt($navContentBox.parent().width());

        if (contentWidth < areaWidth) {
            $(".nav-btn").addClass('hide');
            $navContentBox.css('left', 0)
        } else {
            $(".nav-btn").removeClass('hide')
        }
    }

    // 主页打开初始化时显示第一个系统的菜单
    // $('.systemName').eq('0').trigger('click');
    $('.nav-group li').eq('0').trigger('click');
    //设置可拖拽并设置松开时返回原位置
    // var indicator = $('<div class="indicator">>></div>').appendTo('body');
    // 显示系统首页
    /*setTimeout(function () {
     var indexTab = [];
     indexTab.iconCls = "icon-house";
     indexTab.text = "系统门户";
     var portal = $.getUrlParam("portal");
     if (portal == "system" || portal == null) portal = "system";
     indexTab.url = "html/portal/index.html";
     indexTab.closable = false;
     indexTab.border = false;
     addTab(indexTab);
     }, 1);*/

});


// 折叠左边的菜单栏
function hideWest(isShow) {
    var panel = $('#index_layout').iLayout('panel', 'west');
    var westCollapsed = panel.panel('options').collapsed;
    if (westCollapsed === false) {
        $('#index_layout').iLayout('collapse', 'west');
        $("#MyCollapseMenu").children('span').removeClass('fa-chevron-circle-left').addClass('fa-chevron-circle-right');
    }
}

// 展示左边菜单栏
function showWest(isShow) {
    var panel = $('#index_layout').iLayout('panel', 'west');
    var westCollapsed = panel.panel('options').collapsed;
    if (westCollapsed === true) {
        $('#index_layout').iLayout('expand', 'west');
        $("#MyCollapseMenu").children('span').removeClass('fa-chevron-circle-right').addClass('fa-chevron-circle-left');
    }
}

// Tab菜单操作
function tabMenuOprate(menu, type) {
    var allTabs = $('#index_tabs').iTabs('tabs');
    var allTabtitle = [];
    $.each(allTabs, function (i, n) {
        var opt = $(n).iPanel('options');
        if (opt.closable)
            allTabtitle.push(opt.title);
    });
    var curTabTitle = $(menu).data("tabTitle");
    var curTabIndex = $('#index_tabs').iTabs("getTabIndex", $('#index_tabs').iTabs("getTab", curTabTitle));
    switch (type) {
        case "1"://关闭当前
            if (curTabIndex > 0) {
                $('#index_tabs').iTabs("close", curTabTitle);
                return false;
                break;
            } else {
                $.iMessager.show({
                    title: '操作提示',
                    msg: '首页不允许关闭！'
                });
                break;
            }
        case "2"://全部关闭
            for (var i = 0; i < allTabtitle.length; i++) {
                $('#index_tabs').iTabs('close', allTabtitle[i]);
            }
            break;
        case "3"://除此之外全部关闭
            for (var i = 0; i < allTabtitle.length; i++) {
                if (curTabTitle != allTabtitle[i])
                    $('#index_tabs').iTabs('close', allTabtitle[i]);
            }
            $('#index_tabs').iTabs('scrollBy', 10);
            $('#index_tabs').iTabs('select', curTabTitle);
            break;
        case "4"://当前侧面右边
            for (var i = curTabIndex; i < allTabtitle.length; i++) {
                $('#index_tabs').iTabs('close', allTabtitle[i]);
            }
            $('#index_tabs').iTabs('select', curTabTitle);
            break;
        case "5": //当前侧面左边
            for (var i = 0; i < curTabIndex - 1; i++) {
                $('#index_tabs').iTabs('close', allTabtitle[i]);
            }
            $('#index_tabs').iTabs('select', curTabTitle);
            break;
        case "6": //刷新
            var currentTab = $('#index_tabs').iTabs('getSelected');
            var opts = $.data(currentTab[0], 'panel').options;
            if (opts.iframe) {
                var currentIframe = currentTab.find('iframe')[0];
                currentIframe.contentWindow.location.href = currentIframe.src;
            } else {
                $(currentTab[0]).panel('refresh');
            }
            break;
        case "7": //在新窗口打开
            var refresh_tab = $('#index_tabs').iTabs('getSelected');
            var refresh_iframe = refresh_tab.find('iframe')[0];
            window.open(refresh_iframe.src);
            break;
    }

}

//选项卡右键菜单
function findTabElement(target) {
    var $ele = $(target);
    if (!$ele.is("a")) {
        $ele = $ele.parents("a.menu_tab");
    }
    return $ele;
}

//保存页面id的field
var pageIdField = "data-pageId";

function getPageId(element) {
    if (element instanceof jQuery) {
        return element.attr(pageIdField);
    } else {
        return $(element).attr(pageIdField);
    }
}

function findTabTitle(pageId) {
    var $ele = null;
    $(".page-tabs-content").find("a.menu_tab").each(function () {
        var $a = $(this);
        if ($a.attr(pageIdField) == pageId) {
            $ele = $a;
            return false;//退出循环
        }
    });
    return $ele;
}

function getTabUrlById(pageId) {
    var $iframe = findIframeById(pageId);
    return $iframe[0].contentWindow.location.href;
}

function getTabUrl(element) {
    var pageId = getPageId(element);
    getTabUrlById(pageId);
}

function findTabPanel(pageId) {
    var $ele = null;
    $("#index_tabs").find("div.tab-pane").each(function () {
        var $div = $(this);
        if ($div.attr(pageIdField) == pageId) {
            $ele = $div;
            return false;//退出循环
        }
    });
    return $ele;
}

function findIframeById(pageId) {
    return findTabPanel(pageId).children("iframe");
}

function getActivePageId() {
    var $a = $('.page-tabs-content').find('.active');
    return getPageId($a);
}

//激活Tab,通过id
function activeTabByPageId(pageId) {
    $(".menu_tab").removeClass("active");
    $("#index_tabs").find(".active").removeClass("active");
    //激活TAB
    var $title = findTabTitle(pageId).addClass('active');
    findTabPanel(pageId).addClass("active");
    // scrollToTab($('.menu_tab.active'));
    scrollToTab($title[0]);
}



// 退出系统
function logout() {
    $.iMessager.confirm('提示', '确定要退出吗?', function (r) {
        if (r) {
            var self = this;
            var options = {
                url: '/api/services/app/FWUser/UserLoginOut'
            };
            $.iMessager.progress({
                text: '正在退出中...'
            });
            var success = function (result) {
                $.dm.deleteUserInfo();
                window.location.href = '/Home/Login';
            }
            abp.ajax(options).done(success);
        }
    });
}

// 生成左侧导航菜单
function generateMenu(menuId, systemName) {
    if (menuId == "") {
        $.iMessager.show({ title: $.dm.L('操作提示'), msg: $.dm.L('还未设置该系统对应的菜单ID！') });
    } else {
        var allPanel = $("#RightAccordion").iAccordion('panels');
        var size = allPanel.length;
        if (size > 0) {
            for (i = 0; i < size; i++) {
                var index = $("#RightAccordion").iAccordion('getPanelIndex', allPanel[i]);
                $("#RightAccordion").iAccordion('remove', 0);
            }
        }
        var ajaxdata =
        {
            functionGUID: menuId,
            isTopMenu: 1
        };
        var options = {
            url: '/api/services/app/FWFunction/GetFunctionMenu',
            data: ajaxdata
        };
        var success = function (result) {
            data = result.menuDtos;
            $.each(data, function (i, e) {// 循环创建手风琴的项
                var pid = e.pid;
                var isSelected = i == 0 ? true : false;
                $('#RightAccordion').iAccordion('add', {
                    fit: false,
                    title: $.dm.L(e.text),
                    content: "<ul id='tree" + e.id + "' ></ul>",
                    border: false,
                    selected: isSelected,
                    iconCls: e.iconCls
                });
                genChildMenu(e.id)
            });
        }
        abp.ajax(options).done(success);
    }
}

function genChildMenu(menuId) {
    var ajaxdata =
    {
        functionGUID: menuId,
        isTopMenu: 0
    };

    var options = {
        url: '/api/services/app/FWFunction/GetFunctionMenu',
        data: ajaxdata
    };
    var success = function (result) {
        data = result.menuDtos;
        $.each(data, function (index, item) {
            item.text = $.dm.L(item.text);
        })
        $("#tree" + menuId).tree({
            data: data,
            lines: false,
            animate: true,
            onBeforeSelect: function (node) {
                $("#RightAccordion").find("div.tree-node-selected").removeClass("tree-node-selected");
            },
            onClick: function (node) {
                if (node.url) {
                    /*if(typeof node.attributes != "object") {
                     node.attributes = $.parseJSON(node.attributes);
                     }*/
                    addTab(node);
                    createFunctionSet(node.id, node.text, node.url);

                } else {
                    if (node.state == "closed") {
                        $("#tree" + menuId).tree('expand', node.target);
                    } else if (node.state == 'open') {
                        $("#tree" + menuId).tree('collapse', node.target);
                    }
                }
            }
        });
    }
    abp.ajax(options).done(success);
}

//打开Tab窗口
function addTab(params) {
    var t = $('#index_tabs');
    var $selectedTab = t.iTabs('getSelected');
    var selectedTabOpts = $selectedTab.iPanel('options');
    if (topJUI.config.appendRefererParam && params.url) params.url = appendRefererParam(params.url);
    var iframe = '<iframe src="' + params.url + '" scrolling="auto" frameborder="0" style="width:100%;height:100%;"></iframe>';

    var defaults = {
        id: getRandomNumByDef(),
        refererTab: {},
        title: params.text,
        iframe: topJUI.config.iframe,
        onlyInitParse: true,
        iconCls: 'fa fa-file-text-o',
        border: true,
        fit: true,
        closable: true
        //cls: 'leftBottomBorder'
    };
    var opts = $.extend(defaults, params);
    var ifOpts = opts.iframe ? { content: iframe } : { href: params.url };
    opts = $.extend(opts, ifOpts);
    if (!opts.iconCls || opts.iconCls.trim() === '') {
        opts.iconCls = 'fa fa-file-text-o';
    }

    if (t.iTabs('exists', opts.title)) {
        t.iTabs('select', opts.title);
    } else {
        var lastMenuClickTime = $.cookie("menuClickTime");
        var nowTime = new Date().getTime();
        if ((nowTime - lastMenuClickTime) >= 500) {
            $.cookie("menuClickTime", new Date().getTime());
            t.iTabs('add', opts);
        } else {
            $.iMessager.show({
                title: '温馨提示',
                msg: '操作过快，请稍后重试！'
            });
        }
    }
}

function addParentTab(options) {
    var src, title;
    src = options.href;
    title = options.title;

    var tabs = $('#index_tabs');
    if (tabs.iTabs('exists', title)) {
        tabs.iTabs('select', title);
    } else {
        var iframe = '<iframe src="' + src + '" frameborder="0" style="border:0;width:100%;height:100%;"></iframe>';
        tabs.iTabs("add", {
            title: title,
            content: iframe,
            iframe: true,//加上后才能刷新
            closable: true,
            iconCls: 'fa fa-th',
            border: true
        });
    }
}

function modifyPwd() {
    var $pwdDialog = $('<form id="PwdDialog"></form>'); // 创建form表单元素
    // 修改密码窗口
    $pwdDialog.iDialog({
        title: '修改密码',
        iconCls: 'fa fa-key',
        width: 400,
        height: 300,
        href: '/Home/ModifyPassword',
        closed: false,
        cache: false,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            btnCls: 'topjui-btn',
            handler: function () {
                if ($('#PwdDialog').form('validate')) {
                    if ($("#password").val().length < 6) {
                        $.iMessager.alert('警告', '密码长度不能小于6位', 'messager-warning');
                    } else {
                        var formData = $.dm.parseQueryString($("#PwdDialog").serialize());
                        formData.id = $.dm.getUserInfo().id;
                        var self = this;
                        var data = formData;
                        var options = {
                            url: '/api/services/app/FWUser/UpdateByDto',
                            data: data,
                            maskJqSelect: '#PwdDialog',
                        };
                        var success = function (result) {
                            $.iMessager.show({ title: '我的消息', msg: '修改成功', timeout: 2000, showType: 'slide' });// '消息窗口'组件
                            $("#PwdDialog").dialog('destroy');// 销毁dialog面板
                        }
                        abp.ajax(options).done(success);
                    }
                }
            }
        }],
        onOpen: function () {
            $(this).panel('refresh');
        }
    });
};


function chgApp(applicationName, applicationId, ele) {
    var applicationInfo = {
        id: applicationId,
        applicationName: applicationName
    };

    var appInfo = $.dm.getAppInfo(applicationInfo);
    if (appInfo && appInfo.id != applicationId) {
        $.dm.setAppInfo(applicationInfo);
        // 更新用户默认系统
        var options = {
            url: '/api/services/app/FWUser/UpdateByDto',
            async: false,
            data: {
                id: $.dm.getUserInfo().id,
                defaultApplicationGUID: applicationId
            },
        };
        abp.ajax(options).done();
    }

    vmNorth.$options.methods.getMenu.bind(vmNorth)(applicationId);
    $("#mb4").html(applicationName);

    $("#mb4").iMenubutton({
        menu: '#mm4',
        iconCls: 'fa fa-th-large',
        hasDownArrow: true,
        height: '28'
    });
    $(ele).siblings().show();
    $(ele).hide();
}

function chgBU(buName, buId, companyGUID, isFirst, ele) {
    var buInfo = {
        id: buId,
        buName: buName,
        companyGUID: companyGUID
    };
    // 更新用户默认公司
    var options = {
        url: '/api/services/app/FWUser/UpdateByDto',
        async: false,
        data: {
            id: $.dm.getUserInfo().id,
            defaultBuUnitGUID: buId,
            defaultCompanyGUID: companyGUID
        }
    };
    abp.ajax(options).done();

    if (!isFirst) {
        var currentBuInfo = $.dm.getBuInfo();
        if (currentBuInfo && currentBuInfo.id == buId) {
            return;
        } else {
            var tabs = $('#index_tabs').iTabs('tabs');
            $.each(tabs, function (index, currentTab) {
                var opts = $.data(currentTab[0], 'panel').options;
                if (opts.iframe) {
                    var currentIframe = currentTab.find('iframe')[0];
                    currentIframe.contentWindow.location.href = currentIframe.src;
                } else {
                    $(currentTab[0]).panel('refresh');
                }
            })
        }
    }
    $("#mb5").html(buName);
    $("#mb5").iMenubutton({
        menu: '#mm5',
        iconCls: 'fa fa-institution',
        hasDownArrow: true,
        height: '28'
    });
    $.dm.setBuinfo(buInfo);
    $(ele).siblings().show();
    $(ele).hide();
}
var vmNorth = null;
$(function () {
    loadApplication();
    loadBu();
    vmNorth = new Vue({
        el: "#MyTopModule",
        data: {
            moduleData: [],
            selectIndex: 0
        },
        methods: {
            getMenu: function (applicationGUID) {
                var self = this;
                var data = {
                    applicationGUID: applicationGUID
                };
                var options = {
                    url: '/api/services/app/FWApplication2Module/GetMyModule',
                    data: data
                };
                var success = function (result) {
                    self.moduleData = result.dtos;
                    if (result.dtos.length > 0) {
                        //if (self.moduleData[0].moduleName == "前台预订") {
                        //    self.fullModule(self.moduleData[0].moduleName, self.moduleData[0].moduleUrl);
                        //}
                        if (self.moduleData[0].isFullModule == 1) {

                        } else {
                            generateMenu(self.moduleData[0].moduleGUID, self.moduleData[0].moduleName);
                            showWest();
                        }
                    }

                }
                abp.ajax(options).done(success);
            },
            genMenus: function (item, index) {
                if (this.selectIndex != index) {
                    this.selectIndex = index;
                }

                // 如果是全屏打开 那么调用全屏方法
                if (item.isFullModule == 1) {
                    this.fullModule(item.moduleName, item.moduleUrl);
                }
                // 如果有地址 那么直接open
                else if (item.moduleUrl) {
                    window.open(item.moduleUrl);
                } else {
                    generateMenu(item.moduleGUID, item.moduleName);
                    showWest();
                }
            },
            fullModule: function (name, url) {
                // 隐藏左边栏
                hideWest();
                // 打开tab
                $.ei.openNewTab(name, url);

            }, // 全屏模块的展示
            getClass: function (item) {
                var classAry = ['fa'];
                classAry.push(item.moduleIconCls);
                return classAry;
            },

        }
    });


    function loadApplication() {
        var data = {
            pageIndex: 1,
            pageSize: 9999,
            order: "applicationOrderCode asc,createTime asc"
        };
        var options = {
            url: '/api/services/app/FWApplication/GetViewPage',
            data: data
        };
        var success = function (result) {
            if (result.dataList.length > 0) {
                var appInfo = $.dm.getAppInfo();
                var initAppId = result.dataList[0].id;
                var initAppName = result.dataList[0].applicationName;

                if (appInfo && appInfo.id) {
                    // 判断是否在集合里面
                    var item = _.find(result.dataList, function (item, index, lst) { return item.id == appInfo.id });
                    if (item) {
                        initAppId = item.id;
                        initAppName = item.applicationName;
                    }
                }
                $("#mb4").html(initAppName);
                var applicatonHtmls = [];
                $.each(result.dataList, function (index, item) {
                    var html = "";
                    if (initAppId === item.id) {
                        html = "<div style='display:none' data-options=\"iconCls: 'fa fa-info-circle'\" onclick=\"chgApp('{0}','{1}',this)\">{0}</div>";
                    } else {
                        html = "<div data-options=\"iconCls: 'fa fa-info-circle'\" onclick=\"chgApp('{0}','{1}',this)\">{0}</div>";
                    }
                    applicatonHtmls.push(html.replace(/\{0\}/g, item.applicationName).replace('{1}', item.id));
                })
                $("#mm4").html(applicatonHtmls.join(''));
                chgApp(initAppName, initAppId);
            } else {
                $("#mm4").remove();
            }
        }
        abp.ajax(options).done(success);
    }

    function loadBu() {
        var data = {
            pageIndex: 1,
            pageSize: 9999,
            order: "fullCode asc,createTime asc",
            filter: {
                type: "and",
                conditions: [
                    {
                        attribute: "isCompanyBuUnit",
                        datatype: "tinyint",
                        operatoer: "eq",
                        value: 1
                    }
                ]
            }
        };
        var options = {
            url: '/api/services/app/FWBuUnit/GetViewPage',
            data: data
        };
        var success = function (result) {
            if (result.dataList.length > 0) {
                var initBuGUID = result.dataList[0].id;
                var iniBuName = result.dataList[0].buUnitName;
                var companyGUID = result.dataList[0].companyGUID;
                var buInfo = $.dm.getBuInfo();
                // 如果有门店ID那么才保持 没有就不读取
                if (buInfo && buInfo.id && buInfo.id != 'null') {
                    // 判断是否在集合里面
                    var item = _.find(result.dataList, function (item, index, lst) { return item.id == buInfo.id });
                    if (item) {
                        initBuGUID = item.id;
                        iniBuName = item.buUnitName;
                        companyGUID = item.companyGUID
                    }
                }
                var applicatonHtmls = [];
                $.each(result.dataList, function (index, item) {
                    var html = "";
                    if (initBuGUID === item.id) {
                        html = "<div style='display:none' data-options=\"iconCls: 'fa fa-info-circle'\" onclick=\"chgBU('{0}','{1}','{2}',0,this)\">{0}</div>";
                    } else {
                        html = "<div data-options=\"iconCls: 'fa fa-info-circle'\" onclick=\"chgBU('{0}','{1}','{2}',0,this)\">{0}</div>";
                    }
                    applicatonHtmls.push(html.format(item.buUnitName, item.id, item.companyGUID));
                });

                $("#mm5").html(applicatonHtmls.join(''));
                chgBU(iniBuName, initBuGUID, companyGUID, 1);
            } else {
                $("#mm5").remove();
            }
        }
        abp.ajax(options).done(success);
    }
})



var vmUserInfo;
$(function () {
    vmUserInfo = new Vue({
        el: "#userInfo",
        data: {
            UserInfoData: {
                id: $.dm.getUserInfo().id,
                userName: "",
                userImageUrl: "",
                userSign: ""
            },
            serverImgPath: ""
        },
        methods: {
            // 更新用户信息
            updateUserInfo: function () {
                var self = this;
                var data = self.UserInfoData;
                data.userImageUrl = self.serverImgPath;
                var options = {
                    url: '/api/services/app/FWUser/UpdateByDto',
                    data: data,
                };
                var success = function (result) {
                    layer.msg("修改资料成功！");
                    // 更新用户的cookie信息
                    var userInfo = $.dm.getUserInfo();
                    userInfo.userName = data.userName;
                    userInfo.userImageUrl = data.userImageUrl;
                    userInfo.userSign = data.userSign;
                    $.dm.setUserInfo(userInfo);
                    $("#MyUserNameIndex").iMenubutton({
                        iconCls: 'fa fa-user',
                        hasDownArrow: false,
                        text: $.dm.getUserInfo().userName
                    });
                    setTimeout(function () {
                        layer.closeAll()
                    }, 1000)
                }
                abp.ajax(options).done(success);
            },
            // 保存更新用户信息
            saveUserInfo: function () {
                this.updateUserInfo()
            },
            // 关闭用户信息弹框
            closeUserInfoPopup: function () {
                layer.closeAll()
            },
            // 得到当前用户的信息
            getUserInfo: function () {
                this.UserInfoData = {
                    id: $.dm.getUserInfo().id,
                    userName: $.dm.getUserInfo().userName,
                    userImageUrl: $.dm.getUserInfo().userImageUrl,
                    userSign: $.dm.getUserInfo().userSign,
                };
                this.serverImgPath = $.dm.getUserInfo().userImageUrl;
                console.log(this.UserInfoData)
            }
        },
        mounted: function () {
            //this.getUserInfo();
        }
    });
})
function handleUserInfo() {
    layer.open({
        type: 1,
        title: "修改个人信息",
        area: ['600px', '300px'],
        scrollbar: false,
        content: $("#userInfo"),
        success: function () {
            uploadUserImg();
            vmUserInfo.getUserInfo();
        }
    });
}
var isFirst = true;
//上传文件方法
function uploadUserImg() {
    if (isFirst) {
        layui.use('upload', function () {
            var upload = layui.upload;
            upload.render({
                elem: '#uploadImg',
                url: '/api/services/app/File/UploadFile?type=FWuser',
                ext: 'jpg|png|gif',
                choose: function (obj) {
                    // 预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        /* $('#userImg').attr('src', result);*/ //图片链接（base64）
                        vmUserInfo.$data.UserInfoData.userImageUrl = result;
                    });
                },
                done: function (res) {
                    vmUserInfo.$data.serverImgPath = res.result;
                    //如果上传失败
                    if (res.code > 0) {
                        return layer.msg($.dm.L('上传失败'));
                    }
                    ////上传成功
                },
                error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });
            isFirst = false;
        })
    }

}

function chgMyLanguage(url, langName) {
    $.dm.setLangName("YdmCoreLangName", langName);
    if (url) {
        window.location.href = url;
    }
}

// 切换到上一个Tab
function chgPreIndexTab() {
    var tabsJq = $("#index_tabs");
    if (tabsJq.length >= 1) {
        // 获取选中的队列
        var his = tabsJq.data('tabs').selectHis;
        if (his.length > 1) {
            tabsJq.tabs('select', his[his.length - 2]);
        }
    }
}


// 打开查询菜单
function openSearchMenu() {
    if ($("#MySearchMenuDialog").length >= 1) {
        $("#MySearchMenuDialog").iDialog('close');
    } else {
        var $editDialog = $('<form id="MySearchMenuDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '查找菜单',
            width: 750,
            height: 85,
            closed: false,
            cache: false,
            modal: false,
            maximizable: false,
            minimizable: false,
            collapsible: false,
            top: 90,
            border: false,
            draggable: false,
            content: $("#SearchFunctionInPut").html(),
            onOpen: function () {
                $('#SearchFunctionCombox').iCombobox('textbox').focus();
                $('#SearchFunctionCombox').iCombobox('showPanel');
            }
        });
    }
}

function closeCurrentTab() {
    var tabsJq = $("#index_tabs");
    var selectTab = tabsJq.tabs('getSelected');
    var index = tabsJq.tabs('getTabIndex', selectTab);
    tabsJq.tabs('close', index);
}

/**
 * 
 * @param {any} functionId 菜单ID
 * @param {any} functionName 菜单名称
 * @param {any} functionUrl 菜单URL
 */
function createFunctionSet(functionId, functionName, functionUrl) {
    // 异步记录到首页记录中
    var functionSetData = {
        userGUID: $.dm.getUserInfo().id,
        functionGUID: functionId,
        isSiteInner: 1,
        userFunctionSetUrl: functionUrl,
        userFunctionSetName: functionName,
        userFunctionSetSort: 0
    }
    var options = {
        url: '/api/services/app/FWUserFunctionSet/CreateByDto',
        data: functionSetData,
    };
    var success = function (result) {
        // 刷新首页
        var currentTab = $('#index_tabs').iTabs('getTab', 0);
        var opts = $.data(currentTab[0], 'panel').options;
        if (opts.iframe) {
            var currentIframe = currentTab.find('iframe')[0];
            currentIframe.contentWindow.location.href = currentIframe.src;
        } else {
            $(currentTab[0]).panel('refresh');
        }
    };
    abp.ajax(options).done(success);
}

// 连接SignalR
abp.signalr = abp.signalr || {};
abp.signalr.autoConnect = false;
$(function () {
    var chatHub = null;

    abp.signalr.startConnection(abp.appPath + 'signalr-myChatHub', function (connection) {
        chatHub = connection; // Save a reference to the hub
        connection.on('getMessage', function (message) { // Register for incoming messages
            // alert(message);
            console.log(message);
        });
    }).then(function (connection) {
        abp.event.trigger('myChatHub.connected');
    });

    abp.event.on('myChatHub.connected', function () { // Register for connect event
        chatHub.invoke('sendMessage', "hi 我连接了signalR"); // Send a message to the server
    });
})